import axios from "axios";
import { message } from "antd";

const request = axios.create({
  baseURL: "http://localhost:8101",
  timeout: 10000,
  withCredentials: true,
});

//请求拦截器
request.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器
request.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data.code === 40100) {
      // 不是获取用户信息借口,或者不是登录页面,则跳转到登录页面
      if (
        !response.request.responseUrl.includes("user/get/info") &&
        !window.location.pathname.includes("/login")
      ) {
        window.location.href = `/user/login?redirect=${window.location.href}`;
      }
    } else if (data.code !== 0) {
      message.error(data.message ?? "服务器错误");
      throw new Error(data.message ?? "服务器错误");
    }
    return data;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

export default request;
